package com.yxinmiracle.util;

import com.yxinmiracle.file.FastDFSFile;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;

/**
 * @version 1.0
 * @author： YxinMiracle
 * @date： 2021-08-08 13:00
 */

public class FastDFSClient {

    static {
        try {
            ClassPathResource classPathResource = new ClassPathResource("fdfs_client.conf");
            String path = classPathResource.getPath();
            ClientGlobal.init(path);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }

    public static String[] upload(FastDFSFile dfsFile) throws Exception{
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageClient storageClient = new StorageClient(trackerServer,null);

        NameValuePair[] meat_list = new NameValuePair[]{
                new NameValuePair(dfsFile.getName())
        };
        String[] pngs = storageClient.upload_file(dfsFile.getContent(),dfsFile.getExt(),meat_list);
        for (String png : pngs) {
            System.out.println("png = " + png);
        }
        return pngs;
    }



    public static byte[] downFile(String groupName, String remoteFileName) throws Exception {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageClient storageClient = new StorageClient(trackerServer, null);
        byte[] group1s = storageClient.download_file(groupName, remoteFileName);
        return group1s;
    }

    public static boolean deleteFile(String groupName, String remoteFileName) throws Exception {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageClient storageClient = new StorageClient(trackerServer, null);
        int i = storageClient.delete_file(groupName, remoteFileName);
        return i==0;
    }

    public static FileInfo getFile(String groupName, String remoteFileName){
        try {
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer =trackerClient.getConnection();
            StorageClient storageClient = new StorageClient(trackerServer,null);
            return storageClient.get_file_info(groupName,remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
